package com.messtool.view;

import java.util.ArrayList;

import com.messtool.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.TextView;

public class CitySearchView extends FrameLayout {
	/**
	 * gridview的默认列数
	 */
	private static final int DEFAULT_NUMCOLUMNS = 5;

	private Context context;
	private Button cityButton;
	private EditText keyEdit;
	private GridView cityGrid;
	private boolean gridShow = false;
	private Drawable arrow;

	private OnSearchButtonClickListener searchButtonClickListener = null;
	private ArrayList<String> cityList;

	public CitySearchView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		init();
		initViewWithAttr(context, attrs);
		initListener();
	}

	private void initListener() {
		cityButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				gridShow = !gridShow;

				if (gridShow) {
					cityGrid.setVisibility(View.VISIBLE);
					setDrawableRight(cityButton, R.drawable.pull_up);
				} else {
					cityGrid.setVisibility(View.GONE);
					setDrawableRight(cityButton, R.drawable.pull_down);
				}
			}
		});
		Drawable[] drawables = keyEdit.getCompoundDrawables();
		// 取得right位置的Drawable
		// Î 即我们在布局文件中设置的android:drawableRight
		Drawable mRightDrawable = drawables[2];

		// if (mRightDrawable != null)
		keyEdit.setOnTouchListener(new KeyEditTouch());

		cityGrid.setNumColumns(DEFAULT_NUMCOLUMNS);

		cityGrid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				cityButton.setText(cityList.get(arg2));
			}
		});
	}

	private void init() {
		LayoutInflater.from(context).inflate(R.layout.widget_citysearch, this);

		cityButton = (Button) findViewById(R.id.cityButton);
		keyEdit = (EditText) findViewById(R.id.keyEdit);
		cityGrid = (GridView) findViewById(R.id.cityGrid);
		setDrawableRight(cityButton, R.drawable.pull_down);

	}

	private void initViewWithAttr(Context context, AttributeSet attrs) {
		/**
		 * 获得我们所定义的自定义样式属性
		 */
		TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
				R.styleable.CitySearchView, 0, 0);
		int n = a.getIndexCount();
		for (int i = 0; i < n; i++) {
			int attr = a.getIndex(i);
			if (attr == R.styleable.CitySearchView_editTextColor) {
				keyEdit.setTextColor(a.getColor(attr, Color.BLACK));
			} else if (attr == R.styleable.CitySearchView_editText) {
				keyEdit.setText(a.getString(attr));
			} else if (attr == R.styleable.CitySearchView_editHint) {
				keyEdit.setHint(a.getString(attr));
			} else if (attr == R.styleable.CitySearchView_editTextSize) {
				// 默认设置为16sp，TypeValue也可以把sp转化为px
				keyEdit.setHint(a.getDimensionPixelSize(attr, (int) TypedValue
						.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16,
								getResources().getDisplayMetrics())));
			} else if (attr == R.styleable.CitySearchView_editBackgroud) {
				if (a.getResourceId(attr, -1) == -1) {
					keyEdit.setBackgroundColor(a.getColor(attr, Color.WHITE));
				} else
					keyEdit.setBackgroundResource(a.getResourceId(attr, -1));
			} else if (attr == R.styleable.CitySearchView_buttonBackgroud) {
				if (a.getResourceId(attr, -1) == -1) {
					cityButton
							.setBackgroundColor(a.getColor(attr, Color.WHITE));
				} else
					cityButton.setBackgroundResource(a.getResourceId(attr, -1));
			} else if (attr == R.styleable.CitySearchView_editIcon) {
				setDrawableRight(keyEdit, a.getResourceId(attr, -1));
			}

		}
		a.recycle();
	}

	private void setDrawableRight(EditText view, int resourceId) {
		Drawable draw;
		draw = getResources().getDrawable(resourceId);

		Bitmap bitmap = ((BitmapDrawable) draw).getBitmap();
		draw.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
		view.setCompoundDrawables(null, null, draw, null);
	}

	private void setDrawableRight(Button view, int resourceId) {
		Drawable draw;
		draw = getResources().getDrawable(resourceId);

		Bitmap bitmap = ((BitmapDrawable) draw).getBitmap();
		draw.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
		view.setCompoundDrawables(null, null, draw, null);
	}

	public void setEditText(String text) {
		keyEdit.setText(text);
	}

	public String getEditText() {
		return keyEdit.getText().toString();
	}

	public void setButtonText(String text) {
		cityButton.setText(text);
	}

	public String getButtonText() {
		return cityButton.getText().toString();
	}

	private CityGridviewAdapter adapter = null;

	public void setGridData(ArrayList<String> data) {
		cityList = data;
		if (adapter == null) {
			adapter = new CityGridviewAdapter(context);
			cityGrid.setAdapter(adapter);
		} else {
			adapter.notifyDataSetChanged();
		}
	}

	/**
	 * 设置gridview的列数
	 * 
	 * @param num
	 */
	public void setNumColumns(int num) {
		cityGrid.setNumColumns(num);
	}

	/**
	 * 设置搜索按钮点击事件
	 */
	public void setOnSearchButtonClickOnListener(
			OnSearchButtonClickListener onSearchButtonClickListener) {
		this.searchButtonClickListener = onSearchButtonClickListener;
	}

	public interface OnSearchButtonClickListener {
		public void onClick();
	}

	/**
	 * 当手指抬起的位置在搜索的图标的区域 我们将此视为进行搜索操作 getWidth():得到控件的宽度
	 * event.getX():抬起时的坐标(改坐标是相对于控件本身而言的)
	 * getTotalPaddingRight():搜索的图标左边缘至控件右边缘的距离
	 * getPaddingRight():搜索的图标右边缘至控件右边缘的距离 于是: getWidth() -
	 * getTotalPaddingRight()表示: 控件左边到搜索的图标左边缘的区域 getWidth() -
	 * getPaddingRight()表示: 控件左边到搜索的图标右边缘的区域 所以这两者之间的区域刚好是搜索的图标的区域
	 */
	class KeyEditTouch implements OnTouchListener {

		@Override
		public boolean onTouch(View arg0, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_UP:
				boolean isTouch = (event.getX() > (keyEdit.getWidth() - keyEdit
						.getTotalPaddingRight()))
						&& (event.getX() < (keyEdit.getWidth() - keyEdit
								.getPaddingRight()));
				if (isTouch) {
					if (searchButtonClickListener != null)
						searchButtonClickListener.onClick();
					return true;
				}
				break;

			default:
				break;
			}
			return false;
		}

	}

	public class CityGridviewAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		private boolean isDefault = false;

		public CityGridviewAdapter(Context context) {
			this.inflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return cityList.size();
		}

		@Override
		public Object getItem(int position) {
			return cityList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final int index = position;

			if (convertView == null) {
				holder = new ViewHolder();

				convertView = inflater.inflate(
						android.R.layout.activity_list_item, null);
				convertView.setPadding(0, 0, 0, 0);
				holder.textview = (TextView) convertView
						.findViewById(android.R.id.text1);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.textview.setText(cityList.get(position));
			holder.textview.setPadding(0, 0, 0, 0);

			return convertView;
		}

		ViewHolder holder;

		class ViewHolder {
			TextView textview;
		}
	}
}
